const { accountAdd, accountDelete, accountUpdate, accountGet, accountFilter, accountGetAll } = require("../service/accountService");


const accountGetAllApi = async (event, req, res) => {
    let { limit } = event;
    limit = Number(limit);
    if (isNaN(limit) || limit < 0) {
        limit = 1;
    }
    const result = await accountGetAll(limit);
    // console.log(result)
    return result
}

const accountGetApi = async (event, req, res) => {
    const { date_time, type } = event;
    if (!['year', 'month'].includes(type)) {
        throw new Error('type参数错误');
    }
    if (!date_time) {
        throw new Error('date参数错误');
    }
    const result = await accountGet(date_time, type);
    // console.log(result)
    return result
}

const accountAddApi = async (event, req, res) => {
    let { account_type, category_id, amount, date_time, notes } = event;
    amount = Number(amount)
    if (!['收入', '支出'].includes(account_type)) {
        throw new Error('account_type参数错误');
    }
    if (!category_id || isNaN(amount)) {
        throw new Error('参数错误');
    }
    const result = await accountAdd(account_type, category_id, amount, date_time, notes ?? '');
    // console.log(result)
    if (result.affectedRows !== 1) {
        throw new Error('数据库错误,修改失败');
    }
    return null
}

const accountDeleteApi = async (event, req, res) => {
    const { account_id } = event;
    if (!account_id) {
        throw new Error('参数错误');
    }
    const result = await accountDelete(account_id);
    // console.log(result)
    if (result.affectedRows !== 1) {
        throw new Error('数据库错误,修改失败');
    }
    return null
}

const accountUpdateApi = async (event, req, res) => {
    let { account_id, account_type, category_id, amount, date_time, notes } = event;
    amount = Number(amount);
    if (!account_id) {
        throw new Error('参数错误');
    }
    if (!['收入', '支出'].includes(account_type)) {
        throw new Error('account_type参数错误');
    }
    if (!category_id || isNaN(amount) || !date_time || notes === undefined) {
        throw new Error('参数错误');
    }
    const result = await accountUpdate(account_id, account_type, category_id, amount, date_time, notes);
    // console.log(result)
    if (result.affectedRows !== 1) {
        throw new Error('数据库错误,修改失败');
    }
    return null
}

const accountFilterApi = async (event, req, res) => {
    const { date_time, category_id, limit } = event;
    const result = await accountFilter(date_time, category_id, limit);
    // console.log(result)
    return result
}

module.exports = {
    accountGetAllApi,
    accountGetApi,
    accountAddApi,
    accountDeleteApi,
    accountUpdateApi,
    accountFilterApi
}

